<?php
/**
 * @file user.php
 * @brief 
 * 	stores user functions
 */

error_reporting(E_ALL);

/**
 * 检查用户是否已登录
 * @return 
 * 	true - 用户登录了
 * 	false - 用户没登陆
 */
function isLoggedIn(){
	return (isset($_COOKIE["valid_email"]) || isset($_SESSION["valid_email"]));
}

/**
 * 获取已登录用户的email
 * @return 用户email， 若用户未登录返回‘nobody’
 */
function getUserEmail(){
	if(isset($_COOKIE["valid_email"])){
		return $_COOKIE["valid_email"];
	}else if(isset($_SESSION["valid_email"])){
		return $_SESSION["valid_email"];
	}else{
		return 'nobody';
	}
}

/**
 * 根据用户email获取用户信息
 * @return 用户信息array
 */
function getUserByEmail($email){
	return DB::queryFirstRow("SELECT * FROM `account` WHERE `email`=%s",$email);
}
/**
 * 登录用户，成功后跳转至用户首页，失败在$_SESSION["login_error"]中保存错误提示
 * @param $email
 * 	邮箱
 * @param $password
 * 	密码
 * @param $remember
 * 	是否自动登录
 * @return
 * 	true 登录成功， false 登录失败
 */
function login($email , $password, $remember){
	
	if($email && $password){
					$row = DB::queryFirstRow("SELECT * FROM `account` WHERE `email`=%s",$email);
					if($row!=null){
						if($row['is_active'] == 0){
							$_SESSION["login_error"] =  "用户未激活";
							return false;
						}
						$dbemail = $row['email'];
						$dbpassword = $row['password'];
						if($email==$dbemail && md5($password)==$dbpassword){
							if($remember == 'on'){
								//ob_start();
								//cookie must be set before any output
								// 第四个parameter('/')， 是让cookie可以被全站访问
								setcookie("valid_email", $email, time()+COOKIE_END_DAY,'/') or die('cannot set cookie');	
							}else{
								$_SESSION["valid_email"] = $email;
							}
							//record last login time
							$now = date('Y-m-d H:i:s');
							DB::update('account', 
										array(
										'last_login' => $now
										), "email=%s", $email);
							//js_redirect('正在登陆，请稍等……', USER_HOME_URL);
							return true;
						}
						else {
							$_SESSION["login_error"] =  "密码不正确";
							return false;
						}
					}
					else {
						$_SESSION["login_error"] = "用户不存在";
						return false;
					}
				}
				else{
					$_SESSION["login_error"] = "请输入用户名和密码";
					return false;
				}
}


/**
 * 注册用户，成功后发送激活邮件并跳转至注册成功页面
 * @param $email
 * 	邮箱
 * @param $password
 * 	密码
 * @param $password_confirm
 * 	确认密码
 * @return
 * 	true 注册成功， false 注册失败
 */
function register($email , $password, $password_confirm){
	require_once(ROOT_DIR.'libs/securimage/securimage.php');
	$securimage = new Securimage();
	if ($securimage->check($_POST['captcha_code']) == false) {
	  // the code was incorrect
	  // you should handle the error so that the form processor doesn't continue
	
	  // or you can use the following code if there is no validation or you do not know how
	  echo "验证码不正确";
	  return false;
	}
	$namecheck = DB::queryFirstRow("SELECT `email` FROM `account` WHERE `email` =%s",$email);
	
    $checkEmail = filter_var( $email, FILTER_VALIDATE_EMAIL );

	
	if($namecheck!=null){
		echo "此账户已经存在";
	}else{
		if($email && $password && $password_confirm){
			if($checkEmail){
			/*-----------Check email type---------------------------*/
				if($password==$password_confirm){
					if(strlen($password)>25||strlen($password)<6){
						echo "密码必须大于6位并且小于25位";
					}
					else{
						$password = md5($password);
						$password_confirm = md5($password_confirm);
						$activation_key = generateKey();
						$forgot_password_key = generateKey();
						$registered_on = date("Y-m-d H:i:s");
						
						//$queryreg = mysql_query("INSERT INTO `account` (`email`,`password`,`activation_key`,`forgot_pass_key`,`registered_on`)
							//						VALUES('$email','$password','$activation_key','$forgot_password_key','$registered_on')");
						
						DB::insert('account',array(
							'email' 			=> $email,
							'password'			=> $password,
							'activation_key' 	=> $activation_key,
							'forgot_pass_key' 	=> $forgot_password_key,
							'registered_on' 	=> $registered_on,
							'is_rookie'			=> 1
						));
						$user_id = DB::insertId();
						
						sendActivationEmail($user_id,$activation_key,$email);
						//email已送出，跳转至提示页面
						js_redirect('恭喜注册成功！',HOME_URL.'user/signup_success.php?uid='.$user_id);
						return true;
					}	
				}
				else {
					echo "两次输入密码不一致";
				}
			}
			else{
				echo "邮箱的格式错误";
			}
		}
		else {
			echo "请全部填写";
		}
	}
	return false;
}

/**
 * 随机生成一个10位string
 * @return random key 
 */
function generateKey(){
	return substr(md5(time()*rand()),0,10);
}

/**
 * 利用php mail function发送email
 * @param $to
 * 	收件人邮箱地址
 * @param $subject
 * 	主题
 * @param $message
 * 	内容
 * 
 * @return 
 * 	true 邮件送出，false 错误
 */
function sendEmail($to, $subject, $message){

	$headers = "From: " . strip_tags('no-reply@collarconnect.com') . "\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-Type: text/html;charset=utf-8\r\n";
	
	return mail($to,$subject,$message,$headers);
}

/**
 * 发送激活邮件
 * @param $user_id
 * 	注册用户时生成的id
 * @param $activation_key
 *  激活码
 * @param $recipient
 *  用户邮箱
 * 
 */
function sendActivationEmail($user_id,$activation_key, $recipient){
	$activation_link = HOME_URL.'user/activation.php?id='.$user_id.'&key='.$activation_key;
	$message = str_replace('{activation_link}',$activation_link,file_get_contents(ROOT.'templates/activation_email.php'));
	return sendEmail($recipient,'\(≧▽≦)/用户激活邮件', $message);
}

/**
 * 激活用户，
 * @param $user_id
 * 	用户id
 * @param $activation_key
 * 	激活码
 * @return 
 * 	true 激活成功，false 激活失败
 */
function activateUser($user_id, $activation_key){
	//check if user informaiton match
	$user_row = DB::queryFirstRow("SELECT * FROM `account` WHERE `activation_key` =%s AND `id`=%i",$activation_key,$user_id);
	
	if($user_row == null){
		echo "用户认证错误";
		return false;
	}
	if($user_row['is_active'] == 1){
		echo '此账户已激活，请点击<a href="'.HOME_URL.'main/">这里</a>登陆';
		return false;
	}
	DB::update('account', 
				array(
					'is_active' => '1'
				), 
				"id=%i", $user_id);
	  
  	if(DB::affectedRows()==0){
		echo "激活不成功";
		return false;
	}
	
	//激活成功 update activation key
	echo '用户已激活，请点击<a href="'.HOME_URL.'main/">这里</a>登陆';
	return true;
	
}

/**
 * 发送忘记密码email
 * @param $user_id
 * 	用户id
 * @param $recipient
 * 	收件人
 * @param $forgot_key
 * 	忘记密码key
 */
function sendForgotPassEmail($user_id,$recipient, $forgot_key){
	
}

?>